package com.tongxin.van.frameworkcanary.utils;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AppCompatDialog;
import android.view.Window;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;

import com.tongxin.van.frameworkcanary.R;
import com.yanzhenjie.permission.AndPermission;

import java.io.File;

import okhttp3.internal.http2.StreamResetException;

/**
 *
 * author: VanyLiu
 * email: 13212674795@163.com
 * description: 用于下载视频
 *
**/
public class DownloadUtils {
    /**
     * 下载视频
     */
    public static void downloadVideo(Activity activity, String videoUrl) {
        //弹出正在下载对话框
        final Dialog dialog = new AppCompatDialog(activity);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.setCancelable(false);
        dialog.setContentView(R.layout.dialog_upload);
        dialog.findViewById(R.id.btn_cancel).setOnClickListener(v -> {
            OkGo.getInstance().cancelTag(videoUrl);
            dialog.dismiss();
        });
        final TextView progressTv = dialog.findViewById(R.id.tv_progress);
        progressTv.setText("下载进度：0%");
        dialog.show();

        AndPermission.with(activity)
                .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .onGranted(permissions -> {
                    String destFileDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getAbsolutePath();
                    String destFileName = System.currentTimeMillis() + ".mp4";
                    OkGo.<File>get(videoUrl)
                            .tag(videoUrl)
                            .execute(new FileCallback(destFileDir, destFileName) {

                                @Override
                                public void downloadProgress(Progress progress) {
                                    progressTv.setText("下载进度：" + (int) (progress.fraction * 100) + "%");
                                }

                                @Override
                                public void onSuccess(Response<File> response) {
                                    ToastUtils.showShort("下载成功");
                                    dialog.dismiss();
                                    activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(response.body().getPath()))));
                                }

                                @Override
                                public void onError(Response<File> response) {
                                    if (response.getException() instanceof StreamResetException
                                            && ((StreamResetException) response.getException()).errorCode.httpCode == 8) {
                                        ToastUtils.showShort("已取消下载");
                                    } else {
                                        ToastUtils.showShort("下载失败");
                                    }
                                    FileUtils.deleteFile(new File(destFileDir, destFileName));
                                    dialog.dismiss();
                                }
                            });
                })
                .onDenied(permissions -> ToastUtils.showShort("获取权限失败，请重试"))
                .start();


    }
}
